<template>
  <view class="seckill-page">
    <!-- 顶部状态栏 -->
    <view class="top-banner">
      <view class="banner-content">
        <view class="fire-icon">🔥</view>
        <view class="banner-text">
          <text class="main-title">限时秒杀</text>
          <text class="sub-title">超值优惠·限时抢购</text>
        </view>
        <view class="timer-box">
          <text class="ending-text">距结束</text>
          <view class="countdown">
            <text class="time-unit">{{ timeLeft.hours }}</text>
            <text class="separator">:</text>
            <text class="time-unit">{{ timeLeft.minutes }}</text>
            <text class="separator">:</text>
            <text class="time-unit">{{ timeLeft.seconds }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 选项卡 -->
    <view class="tabs-container">
      <scroll-view scroll-x class="tabs-scroll">
        <view class="tabs">
          <text
            v-for="(tab, index) in tabs"
            :key="index"
            :class="['tab-item', { active: currentTab === index }]"
            @click="switchTab(index)"
          >
            {{ tab.name }}
            <text v-if="tab.count > 0" class="tab-count">{{ tab.count }}</text>
          </text>
        </view>
      </scroll-view>
    </view>

    <!-- 活动列表 -->
    <scroll-view
      scroll-y
      class="list-container"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore"
    >
      <!-- 加载状态 -->
      <view v-if="loading && seckillList.length === 0" class="loading-container">
        <u-loading-icon></u-loading-icon>
        <text class="loading-text">正在加载中...</text>
      </view>

      <!-- 秒杀列表 -->
      <template v-else>
        <template v-if="filteredList.length > 0">
          <view class="seckill-list">
            <seckill-item
              v-for="item in filteredList"
              :key="item.seckillId"
              :item="item"
              @click="goToDetail(item)"
              @buy="handleBuy"
            />
          </view>
        </template>

        <!-- 空状态 -->
        <view v-else class="empty-container">
          <image src="/static/empty-seckill.png" class="empty-image" mode="widthFix" />
          <text class="empty-title">暂无秒杀活动</text>
          <text class="empty-desc">精彩活动即将开启，敬请期待</text>
          <button class="refresh-btn" @click="onRefresh">刷新试试</button>
        </view>
      </template>

      <!-- 加载更多 -->
      <view v-if="hasMore && !loading" class="load-more" @click="loadMore">
        <text class="load-more-text">点击加载更多</text>
      </view>
    </scroll-view>

    <!-- 底部浮动按钮 -->
    <view class="floating-btn" @click="scrollToTop">
      <u-icon name="arrow-up" size="40" color="#fff" />
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import SeckillItem from '@/components/seckill-item.vue'
import { getSeckillList, buySeckill, getSeckillRealTimeStock } from "@/api/seckill"
import { getDishListByIds, getDishById } from "@/api/dish"

// 响应式数据
const currentTab = ref(0)
const seckillList = ref([])
const loading = ref(true)
const refreshing = ref(false)
const hasMore = ref(true)
const page = ref(1)

// 倒计时
const timeLeft = reactive({
  hours: '02',
  minutes: '30',
  seconds: '45'
})

// 选项卡配置
const tabs = reactive([
  { name: '全部活动', status: '', count: 0 },
  { name: '即将开始', status: 1, count: 0 },
  { name: '正在进行', status: 3, count: 0 },
  { name: '已经结束', status: 2, count: 0 }
])

// 计算过滤后的列表
const filteredList = computed(() => {
  if (currentTab.value === 0) return seckillList.value
  
  const targetStatus = tabs[currentTab.value].status
  return seckillList.value.filter(item => item.status === targetStatus)
})

let countdownTimer = null

onMounted(() => {
  // 检查是否已扫码
  checkScanStatus()
  loadData()
  startCountdown()
  
  // 监听购买成功事件
  uni.$on('seckillPurchaseSuccess', handlePurchaseSuccess)
})

// 处理购买成功事件
function handlePurchaseSuccess(eventData) {
  console.log('收到购买成功事件:', eventData)
  
  if (eventData && eventData.releaseId) {
    // 找到对应的秒杀项目并更新库存
    const targetItem = seckillList.value.find(item => 
      item.releaseId === eventData.releaseId || item.seckillId === eventData.releaseId
    )
    
    if (targetItem) {
      const purchasedQuantity = eventData.purchasedQuantity || 1
      
      // 更新库存
      if (targetItem.seckillQuantity !== undefined) {
        targetItem.seckillQuantity = Math.max(0, targetItem.seckillQuantity - purchasedQuantity)
      }
      if (targetItem.stock !== undefined) {
        targetItem.stock = Math.max(0, targetItem.stock - purchasedQuantity)
      }
      
      console.log('列表页库存已更新:', targetItem)
    }
  }
}

// 检查扫码状态
function checkScanStatus() {
  const cachedStoreId = uni.getStorageSync('storeId')
  const cachedTableNo = uni.getStorageSync('tableNo')
  
  if (!cachedStoreId || !cachedTableNo) {
    uni.showModal({
      title: '温馨提示',
      content: '请先扫描桌上的二维码再开始使用',
      showCancel: false,
      confirmText: '去扫码',
      success: () => {
        uni.switchTab({
          url: '/pages/scanCode/scanCode'
        })
      }
    })
    return false
  }
  return true
}

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
  
  // 移除事件监听
  uni.$off('seckillPurchaseSuccess', handlePurchaseSuccess)
})

// 启动倒计时
function startCountdown() {
  countdownTimer = setInterval(() => {
    let seconds = parseInt(timeLeft.seconds)
    let minutes = parseInt(timeLeft.minutes)
    let hours = parseInt(timeLeft.hours)
    
    if (seconds > 0) {
      seconds--
    } else if (minutes > 0) {
      seconds = 59
      minutes--
    } else if (hours > 0) {
      seconds = 59
      minutes = 59
      hours--
    } else {
      // 倒计时结束，刷新数据
      loadData()
      hours = 23
      minutes = 59
      seconds = 59
    }
    
    timeLeft.seconds = String(seconds).padStart(2, '0')
    timeLeft.minutes = String(minutes).padStart(2, '0')
    timeLeft.hours = String(hours).padStart(2, '0')
  }, 1000)
}

// 加载数据
function loadData() {
  loading.value = true
  getSeckillList().then(res => {
    console.log('秒杀列表响应:', res)
    // 直接从响应中获取seckillList
    if (res && res.seckillList) {
      const seckillData = res.seckillList || []
      // 获取所有菜品ID
      const dishIds = seckillData.map(item => item.dishId).filter(id => id)
      
      if (dishIds.length > 0) {
        console.log('准备获取菜品信息，dishIds:', dishIds)
        
        // 去重dishIds，避免重复请求
        const uniqueDishIds = [...new Set(dishIds)]
        console.log('去重后的dishIds:', uniqueDishIds)
        
        // 使用批量接口获取菜品信息
        getDishListByIds(uniqueDishIds).then(dishRes => {
          console.log('批量菜品信息响应:', dishRes)
          if (dishRes && dishRes.dishList) {
            const dishList = dishRes.dishList || []
            console.log('获取到的菜品列表:', dishList)
            
            // 创建菜品信息映射
            const dishMap = {}
            dishList.forEach(dish => {
              dishMap[dish.dishId] = dish
            })
            console.log('菜品映射表:', dishMap)
            
            // 合并秒杀数据和菜品数据
            seckillList.value = seckillData.map(seckill => {
              const dish = dishMap[seckill.dishId]
              return {
                ...seckill,
                dishName: dish?.dishName || `商品${seckill.dishId}`,
                dishImg: dish?.dishImg,
                originalPrice: dish?.price || (seckill.seckillPrice * 1.5).toFixed(2),
                details: dish?.details,
                originalSeckillQuantity: seckill.seckillQuantity // 保存原始库存数量
              }
            })
          } else {
            console.warn('批量接口返回数据格式异常:', dishRes)
            // 如果获取菜品信息失败，使用原始秒杀数据
            seckillList.value = seckillData
          }
          updateTabCounts()
          console.log('合并后的秒杀列表数据:', seckillList.value)
          
          // 获取所有秒杀项目的实时库存
          refreshAllRealTimeStock()
        }).catch(error => {
          console.error('获取菜品信息失败:', error)
          console.error('错误详情:', JSON.stringify(error))
          
          // 如果批量接口失败，尝试使用单个接口获取第一个菜品信息
          const firstDishId = uniqueDishIds[0]
          if (firstDishId && typeof firstDishId === 'number') {
            console.log('批量接口失败，尝试单个接口，dishId:', firstDishId)
            getDishById(firstDishId).then(dishRes => {
              console.log('单个菜品信息响应:', dishRes)
              if (dishRes && dishRes.dish) {
                const dish = dishRes.dish
                
                // 只处理第一个菜品，其他的使用默认信息
                seckillList.value = seckillData.map(seckill => {
                  if (seckill.dishId === firstDishId) {
                    return {
                      ...seckill,
                      dishName: dish.dishName || `商品${seckill.dishId}`,
                      dishImg: dish.dishImg,
                      originalPrice: dish.price || (seckill.seckillPrice * 1.5).toFixed(2),
                      details: dish.details
                    }
                  } else {
                    return {
                      ...seckill,
                      dishName: `商品${seckill.dishId}`,
                      originalPrice: (seckill.seckillPrice * 1.5).toFixed(2)
                    }
                  }
                })
              } else {
                seckillList.value = seckillData
              }
              updateTabCounts()
            }).catch(singleError => {
              console.error('单个接口也失败:', singleError)
              seckillList.value = seckillData
              updateTabCounts()
            })
          } else {
            seckillList.value = seckillData
            updateTabCounts()
          }
        })
      } else {
        seckillList.value = seckillData
        updateTabCounts()
      }
    } else if (res.data && res.data.code === 200) {
      // 兼容其他可能的数据结构
      seckillList.value = res.data.data?.seckillList || res.data.seckillList || []
      updateTabCounts()
      console.log('秒杀列表数据:', seckillList.value)
    } else {
      uni.showToast({ title: res.data?.message || '加载失败', icon: 'none' })
    }
  }).catch(error => {
    console.error('加载秒杀列表失败:', error)
    uni.showToast({ title: '网络错误', icon: 'none' })
  }).finally(() => {
    loading.value = false
    refreshing.value = false
  })
}

// 更新选项卡数量
function updateTabCounts() {
  tabs[0].count = seckillList.value.length
  tabs[1].count = seckillList.value.filter(item => item.status === 1).length
  tabs[2].count = seckillList.value.filter(item => item.status === 3).length
  tabs[3].count = seckillList.value.filter(item => item.status === 2).length
  
  console.log('选项卡统计:', {
    total: tabs[0].count,
    upcoming: tabs[1].count, 
    active: tabs[2].count,
    ended: tabs[3].count
  })
  console.log('当前选中选项卡:', currentTab.value)
  console.log('过滤后的列表:', filteredList.value)
}

// 切换选项卡
function switchTab(index) {
  currentTab.value = index
}

// 下拉刷新
function onRefresh() {
  refreshing.value = true
  page.value = 1
  loadData()
}

// 加载更多
function loadMore() {
  if (!hasMore.value || loading.value) return
  
  page.value++
  // 这里可以实现分页加载逻辑
  // loadData()
}

// 跳转详情页
function goToDetail(item) {
  console.log('点击的秒杀项目:', item)
  
  // 根据数据结构判断是门店秒杀还是系统秒杀
  const id = item.releaseId || item.seckillId
  
  console.log('提取的ID:', id, 'releaseId:', item.releaseId, 'seckillId:', item.seckillId)
  
  if (item.releaseId) {
    // 门店秒杀，使用缓存方式传递数据
    const seckillData = {
      releaseId: item.releaseId,
      dishId: item.dishId || '',
      seckillPrice: item.seckillPrice || '',
      seckillQuantity: item.seckillQuantity || '',
      purchaseLimit: item.purchaseLimit || '',
      startTime: item.startTime || '',
      endTime: item.endTime || '',
      status: item.status || '',
      dishName: item.dishName || '',
      dishImg: item.dishImg || '',
      originalPrice: item.originalPrice || '',
      details: item.details || '',
      originalSeckillQuantity: item.originalSeckillQuantity || item.seckillQuantity // 传递原始库存数量
    }
    
    // 将数据存储到本地缓存
    uni.setStorageSync('currentSeckillDetail', seckillData)
    console.log('存储秒杀详情数据到缓存:', seckillData)
    
    // 只传递必要的ID参数
    uni.navigateTo({
      url: `/pages/seckill/detail?releaseId=${item.releaseId}&type=store`
    })
  } else {
    // 系统秒杀
    console.log('系统秒杀跳转，seckillId:', id)
    uni.navigateTo({
      url: `/pages/seckill/detail?seckillId=${id}&type=system`
    })
  }
}

// 处理购买
function handleBuy(item) {
  uni.showLoading({ title: '抢购中...', mask: true })
  
      const userId = uni.getStorageSync('userId')
    if (!userId) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }
  const cachedStoreId = uni.getStorageSync('storeId') || 3
  const cachedTableNo = uni.getStorageSync('tableNo') || 2
  
  const params = {
    releaseId: parseInt(item.releaseId),
    userId: String(userId),
    quantity: 1,
    limit: parseInt(item.purchaseLimit) || 1,
    dishId: parseInt(item.dishId),
    seckillPrice: parseFloat(item.seckillPrice),
    dishName: item.dishName || '秒杀商品',
    storeId: parseInt(cachedStoreId),
    tableNumber: parseInt(cachedTableNo)
  }
  
  // 验证必需参数
  if (!params.releaseId || !params.dishId || params.seckillPrice === undefined || params.seckillPrice === null) {
    uni.hideLoading()
    uni.showToast({ title: '参数不完整，请刷新重试', icon: 'none' })
    console.error('参数验证失败:', params)
    return
  }
  
  // 处理数字类型转换，确保不是NaN
  if (isNaN(params.releaseId) || isNaN(params.dishId) || isNaN(params.seckillPrice)) {
    uni.hideLoading()
    uni.showToast({ title: '参数格式错误，请刷新重试', icon: 'none' })
    console.error('参数格式错误:', params)
    return
  }
  
  console.log('购买参数:', params)
  buySeckill(params).then(res => {
    console.log('购买响应:', res)
    
    // 检查响应结构，兼容不同的返回格式
    const isSuccess = res && (res.code === 200 || (res.success === true && res.code === 200))
    const message = res.message || '操作完成'
    
    if (isSuccess) {
      uni.showToast({ 
        title: '抢购成功！', 
        icon: 'success',
        duration: 2000
      })
      
      // 立即更新当前项目的库存显示
      const purchasedQuantity = 1
      if (item.seckillQuantity !== undefined) {
        item.seckillQuantity = Math.max(0, item.seckillQuantity - purchasedQuantity)
      }
      if (item.stock !== undefined) {
        item.stock = Math.max(0, item.stock - purchasedQuantity)
      }
      
      console.log('列表项库存已更新:', item)
      
    } else {
      // 根据不同的错误码显示不同的提示
      let errorMsg = message || '抢购失败'
      
      if (res && res.code === 500) {
        if (message.includes('库存不足')) {
          errorMsg = '商品已售完，请选择其他商品'
        } else if (message.includes('超出限购数量')) {
          errorMsg = '您已达到限购数量，无法继续购买'
        } else if (message.includes('活动未开始')) {
          errorMsg = '活动尚未开始，请耐心等待'
        } else if (message.includes('已结束')) {
          errorMsg = '活动已结束，感谢您的参与'
        }
      }
      
      uni.showToast({ 
        title: errorMsg, 
        icon: 'none',
        duration: 2000
      })
    }
  }).catch(error => {
    console.error('抢购失败:', error)
    uni.showToast({ title: '网络错误', icon: 'none' })
  }).finally(() => {
    uni.hideLoading()
  })
}

// 批量获取实时库存
function refreshAllRealTimeStock() {
  console.log('开始批量获取实时库存')
  
  seckillList.value.forEach((item, index) => {
    if (item.releaseId) {
      getSeckillRealTimeStock(item.releaseId).then(res => {
        console.log(`获取实时库存 releaseId:${item.releaseId}`, res)
        if (res && res.stockCount !== undefined) {
          const realTimeStock = parseInt(res.stockCount)
          
          // 直接更新列表项的库存
          seckillList.value[index].seckillQuantity = realTimeStock
          seckillList.value[index].stock = realTimeStock
          
          console.log(`更新列表项${index}库存:`, realTimeStock)
        }
      }).catch(error => {
        console.error(`获取实时库存失败 releaseId:${item.releaseId}`, error)
      })
    }
  })
}

// 滚动到顶部
function scrollToTop() {
  uni.pageScrollTo({ scrollTop: 0, duration: 300 })
}
</script>

<style scoped>
.seckill-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部横幅 */
.top-banner {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%);
  padding: 40rpx 30rpx 30rpx;
  position: relative;
  overflow: hidden;
}

.top-banner::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translate(-50%, -50%) rotate(0deg); }
  50% { transform: translate(-50%, -50%) rotate(180deg); }
}

.banner-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  z-index: 1;
}

.fire-icon {
  font-size: 60rpx;
  margin-right: 20rpx;
}

.banner-text {
  flex: 1;
}

.main-title {
  display: block;
  color: #ffffff;
  font-size: 40rpx;
  font-weight: bold;
  text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.3);
}

.sub-title {
  display: block;
  color: rgba(255, 255, 255, 0.9);
  font-size: 24rpx;
  margin-top: 8rpx;
}

.timer-box {
  text-align: center;
}

.ending-text {
  display: block;
  color: rgba(255, 255, 255, 0.8);
  font-size: 22rpx;
  margin-bottom: 8rpx;
}

.countdown {
  display: flex;
  align-items: center;
}

.time-unit {
  background: rgba(255, 255, 255, 0.25);
  color: #ffffff;
  padding: 8rpx 12rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: bold;
  min-width: 48rpx;
  text-align: center;
  backdrop-filter: blur(10rpx);
}

.separator {
  color: #ffffff;
  font-weight: bold;
  margin: 0 6rpx;
}

/* 选项卡 */
.tabs-container {
  background: #ffffff;
  padding: 0 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.06);
}

.tabs-scroll {
  white-space: nowrap;
}

.tabs {
  display: flex;
  padding: 20rpx 0;
}

.tab-item {
  position: relative;
  padding: 20rpx 30rpx;
  font-size: 30rpx;
  color: #666666;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #ff6b6b;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background: linear-gradient(90deg, #ff6b6b, #ff8e53);
  border-radius: 2rpx;
}

.tab-count {
  background: #ff6b6b;
  color: #ffffff;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 10rpx;
  margin-left: 8rpx;
}

/* 列表容器 */
.list-container {
  flex: 1;
  padding: 30rpx;
}

.seckill-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
}

.loading-text {
  color: #999999;
  font-size: 28rpx;
  margin-top: 20rpx;
}

/* 空状态 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 30rpx;
}

.empty-image {
  width: 400rpx;
  opacity: 0.6;
}

.empty-title {
  font-size: 32rpx;
  color: #333333;
  font-weight: bold;
  margin: 40rpx 0 16rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #999999;
  margin-bottom: 40rpx;
}

.refresh-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%);
  color: #ffffff;
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 40rpx 0;
}

.load-more-text {
  color: #666666;
  font-size: 26rpx;
}

/* 浮动按钮 */
.floating-btn {
  position: fixed;
  right: 30rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 20rpx rgba(255, 107, 107, 0.4);
  z-index: 999;
}
</style>
